package com.itlong.cloud.controller.system;

import com.itlong.cloud.POJO.DTO.operate.OperateRoleGetPageDTO;
import com.itlong.cloud.POJO.DTO.operate.OperateUserInfoGetPageDTO;
import com.itlong.cloud.POJO.PO.OperateRolePO;
import com.itlong.cloud.POJO.PO.OperateUserInfoPO;
import com.itlong.cloud.POJO.VO.MessageVO;
import com.itlong.cloud.POJO.VO.operate.OperateUserInfoGetUserPageVO;
import com.itlong.cloud.abstracts.BaseController;
import com.itlong.cloud.annotation.AuthAccessRequired;
import com.itlong.cloud.annotation.LoggerInfo;
import com.itlong.cloud.constants.LogDescConstant;
import com.itlong.cloud.enumerate.ecode.BaseErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.OperateErrorCodeEnum;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.user.operate.IOperateRoleServiceClient;
import com.itlong.cloud.user.operate.IOperateUserInfoServiceClient;
import com.itlong.cloud.utils.network.http.HttpProtocolUtil;
import com.itlong.cloud.utils.page.Page;
import com.itlong.cloud.utils.words.StringHandlerUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <desc>
 *      运营-系统-菜单管理控制器
 * </desc>
 *
 * @createDate 2017/09/21
 */
@RestController
@RequestMapping("/system/role")
public class OperateRoleController extends BaseController{
    private static final Logger LOG = LoggerFactory.getLogger(OperateRoleController.class);
    @Autowired
    IOperateRoleServiceClient iOperateRoleServiceClient;

    @Autowired
    IOperateUserInfoServiceClient iOperateUserInfoServiceClient;
    /**
     * <desc>
     *      获取分页列表
     * </desc>
     *
     * @param operateRoleGetPageDTO 查询参数DTO
     * @return messageVO
     * @author Jiaqi.X
     * @createDate 2017/09/25
     */
    @RequestMapping(path = "getPage",method = RequestMethod.POST)
    @ResponseBody
    @AuthAccessRequired
    public Object getRolePage(OperateRoleGetPageDTO operateRoleGetPageDTO){
        MessageVO messageVO;
        try {
            HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            operateRoleGetPageDTO= HttpProtocolUtil.parseRequestParamToDTO(OperateRoleGetPageDTO.class,request);
            if(StringUtils.isNotBlank(operateRoleGetPageDTO.getRoleNum())){
                if(!operateRoleGetPageDTO.getRoleNum().matches("[0-9]{1,50}")){
                    operateRoleGetPageDTO.setRoleNum(" ");
                }else{
                    operateRoleGetPageDTO.setRoleNum(Integer.valueOf(operateRoleGetPageDTO.getRoleNum()).toString());
                }
                if(operateRoleGetPageDTO.getRoleNum().equals("0")){
                    operateRoleGetPageDTO.setRoleNum("");
                }
            }
            Page<OperateRolePO> page=iOperateRoleServiceClient.getPage(operateRoleGetPageDTO);
            page.getRows().forEach(po->{
                po.setRoleNum(StringHandlerUtil.autlSupply(4,po.getRoleNum(),"0"));
            });
            messageVO=new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),page);
        } catch (Exception e) {
            throw new DataAccessException("【运营_系统_角色getPage】获取分页列表失败",e);
        }
        return messageVO;
    }

    /**
     * <desc>
     *      添加角色
     * </desc>
     *
     * @param operateRolePO 角色实体
     * @return messageVO
     * @author Jiaqi.X
     * @createDate 2017/09/25
     */
    @AuthAccessRequired
    @LoggerInfo(operateDesc = LogDescConstant.ROLE_OPERATE_LOG_SAVE)
    @RequestMapping(path = "save",method = RequestMethod.POST)
    @ResponseBody
    public Object saveRole(OperateRolePO operateRolePO){
        MessageVO messageVO;
        try {
            HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            operateRolePO= HttpProtocolUtil.parseRequestParamToDTO(OperateRolePO.class,request);
            //检查角色名是否已存在
            if(iOperateRoleServiceClient.checkRoleNameExist(operateRolePO.getRoleName()) > 0){
                return new MessageVO(OperateErrorCodeEnum.USER_ROLE_NAME_EXIST.getErrorCode());
            }
            iOperateRoleServiceClient.save(operateRolePO);
            messageVO=new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
        } catch (Exception e) {
            throw new DataAccessException("【运营_系统_角色save】添加资源失败",e);
        }
        return messageVO;

    }

    /**
     * <desc>
     *      修改角色
     * </desc>
     *
     * @param operateRolePO 角色实体
     * @return messageVO
     * @author Jiaqi.X
     * @createDate 2017/09/21
     */
    @AuthAccessRequired
    @LoggerInfo(operateDesc = LogDescConstant.ROLE_OPERATE_LOG_UPDATE)
    @RequestMapping(path = "update",method = RequestMethod.POST)
    @ResponseBody
    public Object updateRole(OperateRolePO operateRolePO){
        MessageVO messageVO;
        try {
            HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            operateRolePO= HttpProtocolUtil.parseRequestParamToDTO(OperateRolePO.class,request);
            Integer result=iOperateRoleServiceClient.update(operateRolePO);
            if(result < 0){
                return new MessageVO(OperateErrorCodeEnum.USER_ROLE_NAME_EXIST.getErrorCode());
            }
            messageVO=new MessageVO(operateRolePO.getRoleId(),BaseErrorCodeEnum.SUCCESS.getErrorCode());
        } catch (Exception e) {
            throw new DataAccessException("【运营-_系统_角色update】更新资源失败", e);
        }
        return messageVO;
    }

    /**
     * <desc>
     *      查询单条角色
     * </desc>
     *
     * @param operateRolePO 角色实体
     * @return messageVO
     * @author Jiaqi.X
     * @createDate 2017/09/25
     */
    @RequestMapping(path = "getOne",method = RequestMethod.POST)
    @ResponseBody
    public Object getRole(OperateRolePO operateRolePO){
        MessageVO messageVO;
        try{
            HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            operateRolePO= HttpProtocolUtil.parseRequestParamToDTO(OperateRolePO.class,request);
            operateRolePO=iOperateRoleServiceClient.getOne(operateRolePO);
            messageVO=new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),operateRolePO);
        }catch (Exception e){
            throw new DataAccessException("【运营_系统_角色getOne】获取单条资源失败",e);
        }
        return messageVO;
    }


    /**
     * <desc>
     *      启用或禁用
     * </desc>
     *
     * @param operateRolePO 资源实体
     * @return messageVO
     * @author Jiaqi.X
     * @createDate 2017/09/26
     */
    @AuthAccessRequired
    @LoggerInfo(operateDesc = LogDescConstant.ROLE_OPERATE_LOG_BANORUSE)
    @RequestMapping(path = "banOrUse",method = RequestMethod.POST)
    @ResponseBody
    public Object banOrUseRole(OperateRolePO operateRolePO){
        MessageVO messageVO;
        try{
            HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            operateRolePO= HttpProtocolUtil.parseRequestParamToDTO(OperateRolePO.class,request);
            iOperateRoleServiceClient.update(operateRolePO);
            messageVO=new MessageVO(operateRolePO.getRoleId(),BaseErrorCodeEnum.SUCCESS.getErrorCode());
        }catch (Exception e){
            throw new DataAccessException("【运营_系统_角色banOrUse】启用或禁用失败",e);
        }
        return messageVO;
    }

    /**
     * <desc>
     *      保存角色菜单
     * </desc>
     *
     * @param roleId 角色id
     * @param functionIds 资源id 多个,号分隔
     * @return  messageVO
     * @author Jiaqi.X
     * @createTime 2017/09/26
     */
    @AuthAccessRequired
    @LoggerInfo(operateDesc = LogDescConstant.ROLE_OPERATE_LOG_ALLOT_FUNCTION)
    @RequestMapping(path = "saveRoleFunction",method = RequestMethod.POST)
    @ResponseBody
    public Object saveRoleFunction(String roleId,String functionIds,String assessFunctionIds){
        MessageVO messageVO;
        try{
            HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            roleId=request.getAttribute("roleId")==null?null:request.getAttribute("roleId").toString();
            functionIds=request.getAttribute("functionIds")==null?null:request.getAttribute("functionIds").toString();
            assessFunctionIds = request.getAttribute("assessFunctionIds") == null ? null : request.getAttribute("assessFunctionIds").toString();
            String loginUserId = request.getAttribute("myUserName") == null ? null : request.getAttribute("myUserName").toString();
            iOperateRoleServiceClient.saveRoleFunction(roleId,functionIds,assessFunctionIds,loginUserId);
            messageVO=new MessageVO(String.format("%s|%s|%s",roleId,functionIds,assessFunctionIds),BaseErrorCodeEnum.SUCCESS.getErrorCode());
        }catch (Exception e){
            throw new DataAccessException("【运营_系统_角色saveRoleFunction】保存角色菜单失败",e);
        }
        return messageVO;
    }

    /**
     * <desc>
     *      获取所有角色
     * </desc>
     *
     * @return messageVo
     * @author Jiaqi.X
     * @createDate 2017/09/29
     */
    @RequestMapping(path = "getList",method = RequestMethod.POST)
    @ResponseBody
    public Object getRoleList(String token){
        MessageVO messageVO;
        try{
            HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            token= request.getAttribute("token")==null?null:request.getAttribute("token").toString();
            OperateUserInfoPO userInfoPO=iOperateUserInfoServiceClient.retrieve(token);
            List<OperateRolePO> list=iOperateRoleServiceClient.getList(userInfoPO.getUserId());
            messageVO=new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),list);
        }catch (Exception e){
            throw new DataAccessException("【运营_系统_角色getList】获取所有角色失败",e);
        }
        return messageVO;
    }

    /**
     * <desc>
     *      获取分配人员列表
     * </desc>
     *
     * @param pageDTO1  查询参数DTO
     * @return
     * @author Jiaqi.X
     * @createDate 2017/10/10
     */
    @RequestMapping(path = "getAllotUserPage",method =  RequestMethod.POST)
    @ResponseBody
    public Object getAllotUserPage(OperateUserInfoGetPageDTO pageDTO1){
        MessageVO messageVO;
        try{
            HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            pageDTO1=HttpProtocolUtil.parseRequestParamToDTO(OperateUserInfoGetPageDTO.class,request);
            OperateUserInfoGetPageDTO pageDTO=pageDTO1;
            Page<OperateUserInfoGetUserPageVO> page=iOperateUserInfoServiceClient.getPage(pageDTO1);

            List<OperateUserInfoGetUserPageVO> users =page.getRows();
            //检查是否已拥有该角色
            users.forEach(user->{
                String[] roleIds= StringHandlerUtil.splitString(user.getRoleId());
                if(roleIds!=null) {
                    for (String roleId : roleIds) {
                        if (roleId.equals(pageDTO.getAllotRoleId())) {
                            user.setHaveRole("true");
                            break;
                        }
                    }
                }
            });
            page.setRows(users);
            messageVO=new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),page);
        }catch (Exception e){
            throw new DataAccessException("【运营_系统_角色getAllotUserPage】获取分配人员列表失败",e);
        }
        return messageVO;
    }


    /**
     * <desc>
     *      角色分配用户
     * </desc>
     *
     * @param roleId    角色id
     * @param allotUsers    需要分配的人员id 多个，号分隔
     * @param userIds 当前列表所有人员id 多个，号分隔
     * @return
     * @author Jiaqi.X
     * @createDate 2017/10/10
     */
    @AuthAccessRequired
    @LoggerInfo(operateDesc = LogDescConstant.ROLE_OPERATE_LOG_ALLOT_USER)
    @RequestMapping(path = "saveRoleUsers",method = RequestMethod.POST)
    @ResponseBody
    public Object saveRoleUsers(String roleId,String allotUsers,String userIds){
        MessageVO messageVO;
        try{
            HttpServletRequest request= ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            roleId=request.getAttribute("roleId")==null?null:request.getAttribute("roleId").toString();
            allotUsers=request.getAttribute("allotUsers")==null?null:request.getAttribute("allotUsers").toString();
            userIds=request.getAttribute("userIds")==null?null:request.getAttribute("userIds").toString();
            //判断角色是否被禁用
            OperateRolePO role=new OperateRolePO();
            role.setRoleId(roleId);
            role=iOperateRoleServiceClient.getOne(role);
            if(role.getStatus()!=1){
                return new MessageVO(OperateErrorCodeEnum.ROLE_BAN_ERROR.getErrorCode());
            }
            //没有人员的时候不进行分配
            if(StringUtils.isNotBlank(userIds)) {
                iOperateRoleServiceClient.saveRoleUsers(roleId, allotUsers, userIds);
            }
            messageVO=new MessageVO(String.format("%s|%s|%s",roleId,allotUsers,userIds),BaseErrorCodeEnum.SUCCESS.getErrorCode());
        }catch (Exception e){
            throw new DataAccessException("【运营_系统_角色saveRoleUsers】角色分配用户失败",e);
        }
        return messageVO;
    }
}
